/**
 * Created by chen on 18/5/25.
 */

window.onload = function(){
  $.ajax({
    type: 'GET',
    url: "/allCartList",
    success: function(data){
      var allCartList = data;
      getCartNum(allCartList);
      getTmplShowInView(allCartList);
      var total = getSumTotal(allCartList);
      $("#pay_total").text(total);
      $("#pay_time").text(getPayTime());
      getTmplShowGiftInView(allCartList);
      var save = getSaveMoney(allCartList);
      $("#save").text(save.toFixed(2));
    }
  });
};
function getTmplShowGiftInView(allCartList)
{
  var gift_list = {list : getAllGiftInfo(allCartList)};
  var tpl = document.getElementById('giftTpl').innerHTML;
  document.getElementById('shopping_gift_info').innerHTML = template(tpl, gift_list);

}
function getTmplShowInView(allCartList)
{
  var cart_list = {list : getAllCartList(allCartList)};
  var tpl = document.getElementById('payTpl').innerHTML;
  document.getElementById('cart_list_pay_info').innerHTML = template(tpl, cart_list);
}
var promotion_barcodes = ['ITEM00001','ITEM00006'];//优惠促销barcode 买二送一
function getAllCartList(allCartList)
{
  for(var i = 0; i < allCartList.length; i ++)
  {
    var item_info = allCartList[i];
    var barcode = _.find(promotion_barcodes,function(barcode){
      return barcode == item_info.barcode;
    });
    if (barcode == undefined || item_info.count < 3)
    {
      item_info.subtotal = item_info.price * item_info.count + "元";
    }
    else
    {
      item_info.subtotal = item_info.price * (item_info.count - Math.floor(item_info.count/3))+"元（原价："
        +item_info.price * item_info.count + "元）";
    }
  }
  return allCartList;
}

function getSumTotal(allCartList)
{
  var sum = 0;
  for(var i = 0; i < allCartList.length; i ++)
  {
    sum += allCartList[i].count * allCartList[i].price;
  }
  return sum.toFixed(2);
}
function getPayTime()
{
  return moment().format("YYYY年MM月DD日 HH:mm:ss");
}

function getAllGiftInfo(allCartList)
{
  var all_gift_infos = [];
  for(var i = 0; i < allCartList.length; i ++)
  {
    var item = allCartList[i];
    var find_barcode = _.find(promotion_barcodes, function(barcode){
      return barcode == item.barcode;
    });
    if(find_barcode != undefined)
    {
      var num = Math.floor(item.count/3);
      if (num > 0)
      {
        all_gift_infos.push({type:item.type,name:item.name,count:num});
      }

    }
  }
  return all_gift_infos;
}
function getSaveMoney(allCartList)
{
  var save = 0;
  for(var i = 0; i < allCartList.length; i ++)
  {
    var item = allCartList[i];
    var find_barcode = _.find(promotion_barcodes, function(barcode){
      return barcode == item.barcode;
    });
    if(find_barcode != undefined)
    {
      var num = Math.floor(item.count/3);
      save += item.price * num;
    }
  }
  return save;
}

function config()
{
  $.ajax({
    type: 'POST',
    url: "/emptyCart",
    success: function(data){
    }
  });
  window.location.href = "shopping_list";
}